<?php

class SortScan
{

    public $dir_path;
    public $sorted_dir_path;

    function __construct()
    {
        date_default_timezone_set( 'Europe/Kiev' );
        $this->dir_path        = 'D:/Doc/';
        $this->sorted_dir_path = 'D:/IDriveSync/Common/Scanned_Sorted/';
    }

    function run()
    {
        file_put_contents( basename( __FILE__ ) . '.log.txt', "\n" . 'Run at ' . date( "Y.m.d H:i:s" ), FILE_APPEND );

        if ( $dir = opendir( $this->dir_path ) ) {
            while ( ( $file = readdir( $dir ) ) !== false ) {
                if ( ( $file != '.' ) and ( $file != '..' ) ) {
                    $full_file_name = $this->dir_path . $file;
                    if ( ! is_dir( $full_file_name ) ) {
                        $sorted_sub_dir = date( "Y_m_d", filemtime( $full_file_name ) );
                        $sorted_dir     = $this->sorted_dir_path . $sorted_sub_dir;
                        if ( ! file_exists( $sorted_dir ) ) {
                            mkdir( $sorted_dir, 0777, true );
                        }
//                        echo $full_file_name . ' - ' . date( "Y.m.d H:i:s", filemtime( $full_file_name ) ) . "\n";
                        $sorted_full_file_name = $sorted_dir . '/' . $file;
                        if ( ! file_exists( $sorted_full_file_name ) or
                            ( filemtime( $full_file_name ) > filemtime( $sorted_full_file_name ) )
                        ) {
                            file_put_contents( basename( __FILE__ ) . '.log.txt',
                                "\n" . $full_file_name . ' -> ' . $sorted_full_file_name, FILE_APPEND );
                            copy( $full_file_name, $sorted_full_file_name );
                        }
                    }
                }
            }
            closedir( $dir );
        }
    }

}

$pauseSec = 5 * 60;

$sortScan = new SortScan();

while ( true ) {
    $sortScan->run();
    sleep( $pauseSec );
}
?>
